package com.irdstudio.efp.esb.api.rest.psd.query;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.esb.api.bean.psd.query.req.ContMsgAssembleReqBean;
import com.irdstudio.efp.esb.api.bean.psd.query.resp.ContMsgAssembleRespBean;
import com.irdstudio.efp.esb.api.bean.psd.query.resp.NlsPsdPreCreditResultQueryRespBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.GroupeInterface;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.service.common.repository.PrdRepository;
import com.irdstudio.efp.esb.api.service.psd.apply.DkContMsgAssembleService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.esb.service.vo.DkContMsgAssembleVO;
import com.irdstudio.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;

/**
 * 需求编号：【2019D1218】（普税贷需求）
 * 问题编号：【2019D1218】（普税贷合同要素信息查询）
 * 开发人员：【xiaojunhui】
 * 创建日期：【2020/06/10 10:11】
 * 功能描述：
 */

@RestController
@RequestMapping("esb")
public class ContMsgAssembleController implements EsbController {
    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(ContMsgAssembleController.class);

    @Autowired
    private DkContMsgAssembleService dkContMsgAssembleService;

    @Autowired
    private PrdRepository prdRepository;

    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    @ModelAttribute("contMsgAssembleReqBean")
    public ContMsgAssembleReqBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取ESB请求体！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ContMsgAssembleReqBean.class);
    }


    @PostMapping("/SERVICE_30230006_03")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult bindingResult1,
                                     @Validated({GroupeInterface.psd.class}) @ModelAttribute("contMsgAssembleReqBean") ContMsgAssembleReqBean contMsgAssembleReqBean, BindingResult bindingResult2, Exception exception) {

        // 预授信申请信息查询响应信息
        ContMsgAssembleRespBean respBean = new ContMsgAssembleRespBean();
        try {
            logger.info("======>调用接口【30230006_03】(普税贷合同要素信息查询)开始<======");
            // 参数校验
            validateBean(esbReqServiceBean, bindingResult1, contMsgAssembleReqBean, bindingResult2, exception, logger);

            if (contMsgAssembleReqBean.getContrTp().equals("1")) {
                //用信申请流水号不能为空
                if (StringUtils.isEmpty(contMsgAssembleReqBean.getWthdwApSrlNo())) {
                    throw new BizException("支用申请流水号不能为空");
                }
                //贷款金额不能为空
                if (Objects.isNull(contMsgAssembleReqBean.getLoanAmt())) {
                    throw new BizException("贷款金额不能为空");
                }
                //还款方式不能为空
                if (StringUtils.isEmpty(contMsgAssembleReqBean.getRpymtMd())) {
                    throw new BizException("还款方式不能为空");
                }
            }

            //判断产品信息是否存在并且有效
            PrdInfoVO product = prdRepository.getProduct(contMsgAssembleReqBean.getPdCd());
            // 1	待生效
            // 2	生效
            // 3	失效
            if (Objects.isNull(product) || !"2".equals(product.getPrdStatus())) {
                throw new BizException("产品信息不存在或者产品状态不为生效");
            }
            // 设置系统头对象
            setSysHeadFieldThreadLocal(esbReqServiceBean);

            // 校验合同类型
            if (contMsgAssembleReqBean.getContrTp().equals("1")) {
                //个人借款合同
                // 调用服务获取合同要素
                DkContMsgAssembleVO dkContMsgAssembleVO = dkContMsgAssembleService.assembleTask(contMsgAssembleReqBean.getWthdwApSrlNo(), contMsgAssembleReqBean.getCrAppSrNo(), contMsgAssembleReqBean.getLoanAmt().doubleValue(), contMsgAssembleReqBean.getRpymtMd());
                setRespValue(respBean, dkContMsgAssembleVO);
            } else if (contMsgAssembleReqBean.getContrTp().equals("2")) {
                //个人授信合同
                dkContMsgAssembleService.getSxCtrInfo(contMsgAssembleReqBean.getCrAppSrNo(),respBean);
            } else {
                throw new BizException("非法的合同类型");
            }

            return successHandler(esbReqServiceBean, respBean);
        } catch (BizException e) {
            logger.error("普税贷合同要素信息查询，异常信息：", e.getMessage());
            e.printStackTrace();
            return failureHandler(esbReqServiceBean, respBean, e, EsbRetCodeStandard.JKYDCSJYBTG, e.getMessage());
        } catch (Exception e) {
            logger.error("普税贷合同要素信息查询，异常信息：", "系统异常，请稍后再试");
            e.printStackTrace();
            return failureHandler(esbReqServiceBean, respBean, e, EsbRetCodeStandard.SJCLYC, "系统异常，请稍后再试");
        } finally {
            logger.info("======>调用接口【30230003_116】(普税贷合同要素信息查询)结束<======");
        }
    }

    private void setRespValue(ContMsgAssembleRespBean respBean, DkContMsgAssembleVO dkContMsgAssembleVO) {
        //编号 根据输入的为准
        respBean.setContNo(dkContMsgAssembleVO.getContNo());
        //甲方住所
        respBean.setaAddr(dkContMsgAssembleVO.getZhAddr());
        //甲方邮政编码
        respBean.setaPsno(dkContMsgAssembleVO.getZhZipcode());
        //甲方联系电话
        respBean.setaTelNo(dkContMsgAssembleVO.getZhTel());
        //乙方证件类型
        respBean.setaCertType(dkContMsgAssembleVO.getCertType());
        //乙方住所
        respBean.setbAddr(dkContMsgAssembleVO.getCusAddr());
        //乙方邮编
        respBean.setbPsno(dkContMsgAssembleVO.getCusZipcode());
        //乙方联系电话
        respBean.setbTelNo(dkContMsgAssembleVO.getCusPhone());
        //乙方电子邮箱
        respBean.setbEmail(dkContMsgAssembleVO.getCusEmail());
        //乙方传真
        respBean.setbFax(dkContMsgAssembleVO.getCusTax());
        //乙方证件号码
        respBean.setbCertNo(dkContMsgAssembleVO.getCertCode());
        //合同金额-人民币（大写）
        respBean.setContAmtBig(dkContMsgAssembleVO.getLmtAmtUpper());
        //合同金额-（小写）
        respBean.setContAmtSmal(dkContMsgAssembleVO.getLmtAmtLower());
        //LPR利率
        respBean.setLprRt(dkContMsgAssembleVO.getQuoteRates());
        //基点数
        respBean.setBasePoint(dkContMsgAssembleVO.getLRPR());
        //年利率
        respBean.setAnnualInterestReate(dkContMsgAssembleVO.getyRate());
        //户名
        respBean.setUsername(dkContMsgAssembleVO.getCusName());
        //开户行
        respBean.setOpeningBank(dkContMsgAssembleVO.getOrgName());
        //账号
        respBean.setAccount(dkContMsgAssembleVO.getRecvNo());
        //归还方式索引
        respBean.setRptIndex(dkContMsgAssembleVO.getRepayMethod());
        //授信合同编号
        respBean.setSxContNo(dkContMsgAssembleVO.getLmtContNo());
        //乙方客户姓名
        respBean.setbCusName(dkContMsgAssembleVO.getCusName());
        //身份证号码
        respBean.setCertNo(dkContMsgAssembleVO.getCertCode());
        //签约日期
        respBean.setContractDate(dkContMsgAssembleVO.getSignDate());
    }

    public EsbRespServiceBean successHandler(EsbReqServiceBean esbReqServiceBean, ContMsgAssembleRespBean contMsgAssembleRespBean) {
        // 返回代码
        contMsgAssembleRespBean.setRetStCd(ESBConstant.SUCCESS);
        // 返回信息
        contMsgAssembleRespBean.setRtnMsg("查询成功");
        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                JSONObject.toJSONString(contMsgAssembleRespBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero),
                EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                EsbBizEnums.RetCodeMsg.SUCCESS_MSG.getVALUE());
    }

    public EsbRespServiceBean failureHandler(EsbReqServiceBean esbReqServiceBean, ContMsgAssembleRespBean contMsgAssembleRespBean, Exception exception, EsbRetCodeStandard esbRetCodeStandard,String respFaliStr) {
        logger.error("普税贷预授信申请信息查询接口出现异常，异常信息：" + exception.getMessage());
        contMsgAssembleRespBean.setRetStCd(esbRetCodeStandard.getValue());
        contMsgAssembleRespBean.setRtnMsg(respFaliStr);
        exception.printStackTrace();
        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                JSONObject.toJSONString(contMsgAssembleRespBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteMapNullValue),
                EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                esbRetCodeStandard.getValue(),
                exception.getMessage());
    }

}